package edu.java.day0731;

/**
 * 线程安全：在并发时保证数据的准确性、效率尽可能高
 * synchronized
 *1.同步方法
 * 2、同步块
*/
public class SynTest01 {
    public static void main(String[] args) {
        //一份资源
        SafeWeb12306 web = new SafeWeb12306();
        //多个代理
        new Thread(web, "zyz").start();
        new Thread(web, "ysm").start();
        new Thread(web, "llk").start();
    }

    static class SafeWeb12306 implements Runnable {
        //票数
        private int ticketNums = 10;
        private boolean flag = true;

        public void run() {
            while (flag) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                test();
            }
        }
//线程安全 同步
        public synchronized void test() {
            if (ticketNums <=0) {
                flag = false;
                return;
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "-->" + ticketNums--);
        }


    }
}
